use web_sys::HtmlTextAreaElement;
use yew::prelude::*;

#[derive(Properties, PartialEq)]
pub struct TodoInputProps {
    pub initial_value: String,
    pub on_add_todo: Callback<String>,
}

pub struct TodoInput {
    text: String,
    input_ref: NodeRef,
}

pub enum Msg {
    AddTodo,
    None,
}

impl Component for TodoInput {
    type Message = Msg;
    type Properties = TodoInputProps;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            text: ctx.props().initial_value.clone(),
            input_ref: NodeRef::default(),
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::AddTodo => {
                let text = self
                    .input_ref
                    .cast::<HtmlTextAreaElement>()
                    .expect("text field")
                    .value();
                ctx.props().on_add_todo.emit(text);
                //self.text = String::new(); // Clear the input after adding the todo
                true
            }
            _ => false,
        }
    }

    fn changed(&mut self, ctx: &Context<Self>, old_props: &Self::Properties) -> bool {
        if ctx.props().initial_value != old_props.initial_value {
            self.text = ctx.props().initial_value.clone();
            true
        } else {
            false
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let on_keydown = ctx.link().callback(|e: yew::KeyboardEvent| {
            if e.key() == "Enter" && e.ctrl_key() {
                Msg::AddTodo
            } else {
                Msg::None
            }
        });
        let on_click = ctx.link().callback(|_| Msg::AddTodo);

        html! {
            <div class="w-100 padding-middle">
                <textarea
                    ref={self.input_ref.clone()}
                    value={ctx.props().initial_value.clone()}
                    onkeydown={on_keydown}
                    class="todo-input__textarea w-100"
                    rows="4"
                    style="height:50px;"
                />
                <button onclick={on_click} class="todo-input__button">
                    { "应用(Ctrl+Enter)" }
                </button>
            </div>
        }
    }
}
